from pathlib import Path
import time
import sys

"""
# 通过read方法直接全部读取文件内容
def read_all_content_generator(filename):
   
    file_path = Path(__file__).parent / filename

    print(f"开始读取{file_path}文件")

    with open(file_path, "r", encoding="utf-8") as f:

        content = f.read()

        if content is not None:
            yield content


read_gen = read_all_content_generator("java.log")
content = next(read_gen)
print(content)


#把文件的每一行全部读取到list中
def read_file_with_readlines(filename):
    file_path = Path(__file__).parent / filename

    print(f"开始读取{file_path}文件")

    with open(file_path, "r", encoding="utf-8") as f:
        lines = f.readlines()  # 读取文件所有的行到列表,readlines函数返回的list[str]
        return lines


for line in read_file_with_readlines("java.log"):
    print(line)




# readline逐行读取文件
def gen_read_file_line_by_line(filename):
    file_path = Path(__file__).parent / filename

    print(f"开始读取{file_path}文件")

    with open(file_path, "r", encoding="utf-8") as f:

        while True:
            try:
                line = f.readline()
                if line is not None:
                    yield line
                else:
                    yield None
            except StopIteration as e:
                yield e


line_gen = gen_read_file_line_by_line("java.log")

while True:
    time.sleep(0.3)
    line = next(line_gen)
    if line:
        print("逐行读取的内容为=\t", line)
    else:
        print("文件读取完毕！")
        break

"""

# 通过 for line in file 逐行遍历


def gen_read_line_file(filename):
    file_path = Path(__file__).parent / filename

    with open(file_path, "r", encoding="utf-8") as f:

        for line in f:
            if line is not None:
                yield line
            else:
                yield None


gen_file = gen_read_line_file("java.log")

print(sys.getsizeof(gen_file))

while True:
    try:
        time.sleep(0.5)
        content = gen_file.__next__()  # 等价于next(gen_file)
        print("读取到的内容=", content)
    except StopIteration as e:
        print("end")
        break
